package com.exam.controller;

import com.exam.domain.Field;
import com.exam.domain.Grade;
import com.exam.domain.Rank;
import com.exam.domain.TeacherGrade;
import com.exam.service.interfaces.GradeService;
import com.exam.service.interfaces.QuestionService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jly on 2017/3/2.
 */
@Controller
@RequestMapping("/grade")
public class GradeController {
    @Resource
    private GradeService gradeService;
    @Resource
    private QuestionService questionService;

    /**
     * 进入成绩列表界面
     *
     * @return: 进入成绩列表界面
     * @since: 2017-3-2
     * @author: jly
     */
    @RequestMapping("/gradeLists")
    public String userList(HttpSession session, HttpServletRequest request) {
        if (session.getAttribute("userName") == null) {
            return "redirect:" + UserController.basePath(request);
        }
        return "grade/gradeList";
    }

    /**
     * 查询所有科目
     *
     * @return: 返回数据库科目表所有内容
     * @Since: 2017-3-2
     * @author: jly
     */
    @RequestMapping("/fields")
    @ResponseBody
    public List<Field> allFields() {
        return questionService.queryFields();
    }

    /**
     * 查询所有等级
     *
     * @return: 返回数据库等级表所有内容
     * @Since: 2017-3-2
     * @author: jly
     */
    @RequestMapping("/ranks")
    @ResponseBody
    public List<Rank> allRanks() {
        return gradeService.allRanks();
    }

    /**
     * 查询考试开始时间
     *
     * @return:
     * @Since: 2017-3-19
     * @author: jly
     */
    @RequestMapping("/startTime")
    @ResponseBody
    public List<Grade> startTime() {
        return gradeService.allTime();
    }

    /**
     * 查看成绩列表具体数据
     *
     * @return: 返回成绩列表及相关信息
     * @since: 2017-3-2
     * @author: jly
     */
    @RequestMapping("/List")
    @ResponseBody
    public List<Grade> tabList(String studentname, Integer kindId, Integer rankId, String starttime) {
        if (starttime.equals("考试时间(全部)")) {
            starttime = "";
        }
        List<Grade> gradeLists = gradeService.gradeLists(studentname, kindId, rankId, starttime);
        return gradeLists;
    }

    /**
     * 进入学生成绩统计界面
     *
     * @return: 进入学生成绩统计界面
     * @since: 2017-3-19
     * @author: jly
     */
    @RequestMapping("/statictic")
    @ResponseBody
    public List<String> statictic(Integer kindId2, String starttime2) throws ParseException {
        String endtime;
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        endtime = dateFormat.format(now);
        if (starttime2.equals("考试时间(全部)")) {
            starttime2 = "";
            endtime = new StudentExamController().Time(endtime);
        } else {
            endtime = new StudentExamController().Time(starttime2);
        }
        List<Grade> grades = gradeService.studentGrades2(kindId2, starttime2, endtime);
        List<String> str = new ArrayList<>();
        String fields = "";
        String grade2 = "";
        for (int i = 0; i < grades.size(); i++) {
            if (i == grades.size() - 1) {
                fields += grades.get(i).getCreateTime();
                //    fields += "aaa,";
                grade2 += grades.get(i).getGrade();
            } else {
                fields += grades.get(i).getCreateTime() + ",";
                //    fields += "aaa,";
                grade2 += grades.get(i).getGrade() + ",";
            }

        }
        str.add(fields);
        str.add(grade2);
        return str;
    }

    /**
     * 进入老师判分页面
     *
     * @author jly
     * @since 2017-3-20
     */
    @RequestMapping("/teacherGradeView")
    public String teacherGradeView(HttpServletRequest request) {
        if (request.getSession().getAttribute("userName") == null) {
            return "redirect:" + UserController.basePath(request);
        }
        return "grade/teachergrade";
    }

    /**
     * 查询需要判分的主观题
     *
     * @author jly
     * @since 2017-3-20
     */
    @RequestMapping("/zgtAnswerLists")
    @ResponseBody
    public List<TeacherGrade> teacherGrades() {
        List<TeacherGrade> grades = gradeService.queryteacherGrades();
        return grades;
    }

    /**
     * 将老师判分插入老师分数临时表
     *
     * @param gradeData 具体提交数据
     * @return 0-成功 1-失败
     * @author jly
     * @since 2017-3-20
     */
    @RequestMapping("/giveMark")
    @ResponseBody
    public int giveMark(@RequestParam(value = "gradeData[]") String gradeData) {
        int result = 0;
        boolean giveMark = false;
        boolean endgrade = false;
        String[] str1 = gradeData.split(",");
        String[] str2;
        //所有gradeId
        Integer[] gradeId = new Integer[str1.length];
        int x = 0;
        int y = 0;
        int rank = 0;
        List<TeacherGrade> teachergradelist;
        for (int i = 0; i < str1.length; i++) {
            str2 = str1[i].split("&");
            //给questiongrade赋值
            giveMark = gradeService.giveMarks
                    (Integer.valueOf(str2[0]), Integer.valueOf(str2[1]), Integer.valueOf(str2[2]), str2[3], Integer.valueOf(str2[4]));
            //将当前gradeId放入数组
            gradeId[i] = Integer.valueOf(str2[4]);
        }
        gradeId = uniq(gradeId);
        for (int j = 0; j < gradeId.length; j++) {
            x = 0;
            teachergradelist = gradeService.queryTeacherGradelist(gradeId[j]);
            //根据gradeID查询相关数据，如果 > 1条，得到客观题分数以及每一个主观题分数
            if (teachergradelist.size() > 1) {
                y = teachergradelist.get(0).getKgtgrade();
                for (int k = 0; k < teachergradelist.size(); k++) {
                    x += teachergradelist.get(k).getQuestionGrade();
                }
                if (x + y >= 85) {
                    rank = 1;
                } else if (x + y >= 75 && x + y < 85) {
                    rank = 2;
                } else if (x + y >= 60 && x + y < 75) {
                    rank = 3;
                } else if (x + y < 60) {
                    rank = 4;
                }
            }
            //如果查询结果为一条数据，直接得出客观题分数以及主观题分数
            if (teachergradelist.size() == 1) {
                y = teachergradelist.get(0).getKgtgrade();
                x = teachergradelist.get(0).getQuestionGrade();
                if (x + y >= 85) {
                    rank = 1;
                } else if (x + y >= 75 && x + y < 85) {
                    rank = 2;
                } else if (x + y >= 60 && x + y < 75) {
                    rank = 3;
                } else if (x + y < 60) {
                    rank = 4;
                }
            }
            endgrade = gradeService.updataGrade(gradeId[j], x + y,rank);
        }
        if (giveMark && endgrade) {
            gradeId = uniq(gradeId);
            for (int p = 0; p < gradeId.length; p++) {
                if (gradeService.delteachergrade(gradeId[p])) {
                    result = 1;
                } else {
                    result = 0;
                }
            }
        } else {
            result = 0;
        }
        return result;
    }

    /**
     * 数组去重
     *
     * @author jly
     * @since 2017-3-20
     */
    public Integer[] uniq(Integer[] array) {
        List<Integer> result = new ArrayList<>();
        boolean flag;
        for (int i = 0; i < array.length; i++) {
            flag = false;
            for (int j = 0; j < result.size(); j++) {
                if (array[i].equals(result.get(j))) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                result.add(array[i]);
            }
        }
        Integer[] arrayResult = result.toArray(new Integer[result.size()]);
        return arrayResult;
    }
}
